/**
 * @(#)LinkDao.java, 2008-4-30.
 * Copyright 2008  Program Analysis Research Group(PARG),Institute of Software, Peking University.
 * All rights reserved.
 */
package edu.pku.sei.pgie.persistence.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import edu.pku.sei.pgie.beans.Link;

/**
 * @author HeLi
 */
public class LinkDAO extends DAOStub {

    public LinkDAO() {
        super();
    }

    public List loadLinks() throws SQLException {
        QueryRunner runner = new QueryRunner(dataSource);
        Object result = runner.query("select * from OUTLINK",
                new BeanListHandler(Link.class));
        return (List) result;
    }

    public void clear() throws SQLException {
        QueryRunner runner = new QueryRunner(dataSource);
        runner.update("delete from OUTLINK");
    }

    public List loadInLinks(long codeId) throws SQLException {
        QueryRunner runner = new QueryRunner(dataSource);
        Object result = runner.query(
                "select * from OUTLINK where ENDPOINT = ?", new Long(codeId),
                new BeanListHandler(Link.class));
        return (List) result;
    }

    public List loadOutLinks(long codeId) throws SQLException {
        QueryRunner runner = new QueryRunner(dataSource);
        Object result = runner.query(
                "select * from OUTLINK where STARTPOINT = ?", new Long(codeId),
                new BeanListHandler(Link.class));
        return (List) result;
    }

    public Link createLink(Link link) throws SQLException {
        QueryRunner runner = new QueryRunner(dataSource);
        Long uid = generateUID();
        runner.update("insert into OUTLINK(STARTPOINT,ENDPOINT,TYPE,LINKID)\n"
                + "values(?,?,?,?)", new Object[] {
            new Long(link.getStartPoint()), new Long(link.getEndPoint()),
            link.getType(), uid
        });
        link.setLinkId(uid.longValue());
        return link;
    }
}
